package com.xuecheng.manage_course.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsCode;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.course.*;
import com.xuecheng.framework.domain.course.ext.CategoryNode;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.response.*;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.media.response.MediaCode;
import com.xuecheng.framework.exception.CustomExcetionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.client.CmsClient;
import com.xuecheng.manage_course.dao.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class CouserService {
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    TeachplanRepository teachplanRepository;
    @Autowired
    CourseBaseRepository courseBaseRepository;
    @Autowired
    CourseMarketRepository courseMarketRepository;

    @Autowired
    TeachplanMediaPubRepository teachplanMediaPubRepository;


    //    数据注入
    @Value("${course-publish.dataUrlPre}")
    private String publish_dataUrlPre;
    @Value("${course-publish.pagePhysicalPath}")
    private String publish_page_physicalpath;
    @Value("${course-publish.pageWebPath}")
    private String publish_page_webpath;
    @Value("${course-publish.siteId}")
    private String publish_siteId;
    @Value("${course-publish.templateId}")
    private String publish_templateId;
    @Value("${course-publish.previewUrl}")
    private String previewUrl;

    /**
     * @Description: //   通过id查询到分级目录
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */

    public Teachplan findById(String id) {
        if (StringUtils.isEmpty(id)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Teachplan teachplan = null;
        try {
            teachplan = courseMapper.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        if (StringUtils.isEmpty(teachplan)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        return teachplan;
    }

    /**
     * @Description: 新增课程计划
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public ResponseResult addTeachplan(Teachplan teachplan) {
//        获取上级节点判断是否为空
        String parentid = teachplan.getParentid();
        String courseid = teachplan.getCourseid();
        teachplan.setOrderby(1);
        teachplan.setStatus("0");
        if (StringUtils.isEmpty(parentid)) {
//            父节点为空，自身为根节点,父节点为课程的id
            Teachplan teachplanParentId = this.findByCourseIdAndParentId(courseid, "0");
            teachplan.setParentid(teachplanParentId.getId());
            teachplan.setGrade("2");
            Teachplan save = teachplanRepository.save(teachplan);
            if (StringUtils.isEmpty(save.getId())) {
                throw CustomExcetionCast.getCusException(CommonCode.FAIL);
            }
            return new ResponseResult(CommonCode.SUCCESS);
        }
//       父节点不为空，则直接填写父节点,并且查找到父节点的id

        Optional<Teachplan> optionalTeachplan = teachplanRepository.findById(parentid);
        if (!optionalTeachplan.isPresent()) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }

        Teachplan teachGrade = optionalTeachplan.get();
        String grade = teachGrade.getGrade();
        String gradeSelf = grade.equals("1") ? "2" : "3";
        teachplan.setGrade(gradeSelf);
        Teachplan save = teachplanRepository.save(teachplan);
        if (StringUtils.isEmpty(save.getId())) {
            throw CustomExcetionCast.getCusException(CommonCode.FAIL);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description: //    根据课程id查询父节点
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private Teachplan findTeachplanByCourseid(String courseid) {
        if (StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        List<Teachplan> teachplans = teachplanRepository.findByCourseid(courseid);
        if (StringUtils.isEmpty(teachplans)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        Teachplan teachplan = teachplans.get(0);
        return teachplan;
    }

    /**
     * @Description: //    根据课程id查询基本课程，获取name
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private CourseBase findbyCourseId(String id) {
        Optional<CourseBase> courseBase = courseBaseRepository.findById(id);
        if (!courseBase.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        CourseBase courseBase1 = courseBase.get();
        return courseBase1;
    }

    //    根据课程id和及它的父节点，获取tecahplan的id
    private Teachplan findByCourseIdAndParentId(String courseid, String parentid) {
        List<Teachplan> teachplanList = teachplanRepository.findByCourseidAndParentid(courseid, parentid);
        if (StringUtils.isEmpty(teachplanList)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        Teachplan teachplan = teachplanList.get(0);
        return teachplan;
    }

    /**
     * @Description: //  查询课程列表
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public QueryResponseResult findList(Map map) {
        if (map.isEmpty()||StringUtils.isEmpty(map.get("companyId"))) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Integer page = (Integer) map.get("page");
        Integer size = (Integer) map.get("size");
        String companyId = (String) map.get("companyId");
        if (StringUtils.isEmpty(page) || page < 1) {
            page = 1;
        }
        if (StringUtils.isEmpty(size) || size < 1) {
            page = 7;
        }
        PageHelper.startPage(page, size);
        Page<Map> courseBases = courseMapper.findList(companyId);
        List<Map> baseList = courseBases.getResult();
        long total = courseBases.getTotal();
/*        id:'test01',
                name:'test01',
                pic:''*/
        ArrayList<Map> list = new ArrayList<>();

        QueryResult queryResult = new QueryResult();
        queryResult.setList(baseList);
        queryResult.setTotal(total);
        QueryResponseResult queryResponseResult = new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        return queryResponseResult;
    }

    /**
     * @Description: 查询课程分类列表
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public CategoryNode findCateList() {
        CategoryNode categoryNode = null;
        try {
            categoryNode = courseMapper.findCateList();

        } catch (Exception e) {
            e.printStackTrace();
            throw CustomExcetionCast.getCusException(CommonCode.SERVER_ERROR);
        }
        return categoryNode;
    }

    /**
     * @Description: //  根据id查询课程
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public CourseBase findCourseById(String id) {
        if (StringUtils.isEmpty(id)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(id);
        if (!optionalCourseBase.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        CourseBase courseBase = optionalCourseBase.get();
        return courseBase;
    }

    /**
     * @Description:新增课程
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public ResponseResult addCourse(CourseBase courseBase) {
        String name = courseBase.getName();
//        判断是否有重复的名字
        List<CourseBase> name1 = courseBaseRepository.findByName(name);
        if (!name1.isEmpty()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NAME_REPEAT);
        }
        if (StringUtils.isEmpty(name)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NAMEISNULL);
        }
        String grade = courseBase.getGrade();
        if (StringUtils.isEmpty(grade)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_GRADE_NAMEISNULL);
        }
        String studymodel = courseBase.getStudymodel();
        if (StringUtils.isEmpty(studymodel)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_STUDY_MODEL_NAMEISNULL);
        }
//        判断课程分类是否为空
        CourseBase base = courseBaseRepository.save(courseBase);
        if (StringUtils.isEmpty(base.getId())) {
            throw CustomExcetionCast.getCusException(CommonCode.SERVER_ERROR);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description: 更新课程
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public ResponseResult updateCourse(String id, CourseBase courseBase) {
        if (StringUtils.isEmpty(courseBase.getId())) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        id = courseBase.getId();
        String grade = courseBase.getGrade();
        if (StringUtils.isEmpty(grade)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_GRADE_NAMEISNULL);
        }
        String studymodel = courseBase.getStudymodel();
        if (StringUtils.isEmpty(studymodel)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_STUDY_MODEL_NAMEISNULL);
        }
        String name = courseBase.getName();
        if (StringUtils.isEmpty(name)) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NAMEISNULL);
        }
//        根据id查询课程是否存在
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
        if (!courseBaseOptional.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NULL);
        }
        CourseBase courseBase1 = courseBaseOptional.get();
        if (courseBase1.getName().equals(courseBase.getName())) {
//            根据id直接修改
            return this.update(courseBase);
        }

//        判断是否有重复的名字
        List<CourseBase> name1 = courseBaseRepository.findByName(name);
        if (!name1.isEmpty()) {
//            已存在课程，不能修改
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NAME_REPEAT);
        }
//        根据id进行修改
        return this.update(courseBase);
    }

    /**
     * @Description: 跟新课程私有方法
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private ResponseResult update(CourseBase courseBase) {
        try {
            courseMapper.update(courseBase);
            return new ResponseResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(CommonCode.FAIL);
        }
    }

    ;

    /**
     * @Description: 根据课程id查询营销信息
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public CourseMarket findMarketByCourseId(String id) {
        if (StringUtils.isEmpty(id)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CourseMarket> optionalCourseMarket = courseMarketRepository.findById(id);
        if (!optionalCourseMarket.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        CourseMarket courseMarket = optionalCourseMarket.get();
        return courseMarket;
    }

    /**
     * @Description: 课程营销添加
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public ResponseResult saveMarket(String id, CourseMarket courseMarket) {
        if (courseMarket == null || StringUtils.isEmpty(id)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        String marketId = courseMarket.getId();
        Float price = courseMarket.getPrice();
        String charge = courseMarket.getCharge();
        Date startTime = courseMarket.getStartTime();
        Date endTime = courseMarket.getEndTime();
//       charge 23002
//        valid 24002
        String valid = courseMarket.getValid();

        if (charge.equals("203002")) {
//            收费
            if (price <= 0) {
                throw CustomExcetionCast.getCusException(CourseCode.COURSE_PRICE_ERROR);
            }
        } else {
            if (!charge.equals("203001")) {
                throw CustomExcetionCast.getCusException(CourseCode.COURSE_PRICE_ERROR);
            }
            courseMarket.setPrice(null);
        }
        if (valid.equals("204002")) {
//              指定指定时间段
            if (startTime == null || endTime == null) {
                throw CustomExcetionCast.getCusException(CourseCode.COURSE_TIME_ERROR);
            }
        } else {
            if (!valid.equals("204001")) {
                throw CustomExcetionCast.getCusException(CourseCode.COURSE_TIME_ERROR);
            }
            courseMarket.setStartTime(null);
            courseMarket.setEndTime(null);
        }
//        根据id查询是否存在
        Optional<CourseMarket> optionalCourseMarket = courseMarketRepository.findById(marketId);
        if (!optionalCourseMarket.isPresent()) {
//            不存在直接连接
            courseMarketRepository.save(courseMarket);
            return new ResponseResult(CommonCode.SUCCESS);
        }
        CourseMarket market = optionalCourseMarket.get();
        market.setCharge(charge);
        market.setPrice(price);
        market.setStartTime(startTime);
        market.setEndTime(endTime);
        market.setQq(courseMarket.getQq());
        market.setValid(valid);
//        更新课程营销信息
        courseMarketRepository.save(market);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description: 保存课程id和图片id
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    @Autowired
    CoursePicRepository coursePicRepository;

    public ResponseResult savePic(String fileId, String courseid) {
        if (StringUtils.isEmpty(fileId) || StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CoursePic> optionalCoursePic = coursePicRepository.findById(courseid);
        if (optionalCoursePic.isPresent()) {
//修改
            CoursePic coursePic = optionalCoursePic.get();
            coursePic.setPic(fileId);
            coursePicRepository.save(coursePic);
            return new ResponseResult(CommonCode.SUCCESS);
        }
//        不存在直接添加
        CoursePic coursePic = new CoursePic();
        coursePic.setCourseid(courseid);
        coursePic.setPic(fileId);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description: 查询图片id
     * @Param: courseid
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public FindPicResult findcoursePic(String courseid) {
        if (StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CoursePic> optionalCoursePic = coursePicRepository.findById(courseid);
        if (optionalCoursePic.isPresent()) {
            CoursePic coursePic = optionalCoursePic.get();
            String pic = coursePic.getPic();
            return new FindPicResult(CommonCode.SUCCESS, pic);
        }
        return new FindPicResult(FileSystemCode.FS_PIC_NULL, null);

    }

    /**
     * @Description: 删除课程图片
     * @Param: coureseid
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public ResponseResult deletePic(String courseid) {
        if (StringUtils.isEmpty(courseid) || courseid.isEmpty()) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CoursePic> optionalCoursePic = coursePicRepository.findById(courseid);
        if (optionalCoursePic.isPresent()) {
            coursePicRepository.deleteById(courseid);
            return new ResponseResult(CommonCode.FAIL);
        }
        throw CustomExcetionCast.getCusException(FileSystemCode.FS_PIC_NULL);

    }

    /**
     * @Description: 课程发布数据模型
     * @Param: courseid
     * @return: CourseView
     * @Author: Mr.Yuan
     * @Date:
     */
    public CourseView findAllData(String courseid) {
        if (StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseid);
        if (!optionalCourseBase.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NULL);
        }

        CourseBase courseBase = optionalCourseBase.get();
        Optional<CoursePic> optionalCoursePic = coursePicRepository.findById(courseid);
        if (!optionalCoursePic.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PIC_NULL);
        }
        CoursePic coursePic = optionalCoursePic.get();

        Optional<CourseMarket> optionalCourseMarket = courseMarketRepository.findById(courseid);
        if (!optionalCourseMarket.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_MEDIS_URLISNULL);
        }
        CourseMarket courseMarket = optionalCourseMarket.get();

        TeachplanNode teachplanNode = courseMapper.findById(courseid);
        if (teachplanNode == null) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_TEACH_NULL);
        }
        CourseView courseView = new CourseView();
        courseView.setCourseBase(courseBase);
        courseView.setCourseMarket(courseMarket);
        courseView.setCoursePic(coursePic);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }

    @Autowired
    CmsClient cmsClient;

    /**
     * @Description: 课程预览
     * @Param: courseid
     * @return: 预览url地址
     * @Author: Mr.Yuan
     * @Date:
     */
    public PreviewResult coursePreview(String courseid) {
        if (StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseid);
        if (!optionalCourseBase.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NULL);
        }
        CourseBase courseBase = optionalCourseBase.get();
//        将页面信息存入页面管理数据库
        CmsPage cmsPage = new CmsPage();
        //站点
        cmsPage.setSiteId(publish_siteId);
        //课程预览站点 //模板
        cmsPage.setTemplateId(publish_templateId);
        //页面名称
        cmsPage.setPageName(courseid + ".html");
        // 页面别名
        cmsPage.setPageAliase(courseBase.getName());
        // 页面访问路径
        cmsPage.setPageWebPath(publish_page_webpath);
        // 页面存储路径
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);
        // 数据url
        cmsPage.setDataUrl(publish_dataUrlPre + courseid);
        // 远程请求cms保存页面信息
        try {
            CmsPageResult cmsPageResult = cmsClient.savePageByCourse(cmsPage);
            CmsPage cmsPage1 = cmsPageResult.getCmsPage();
            String pageId = cmsPage1.getPageId();

            return new PreviewResult(CommonCode.SUCCESS, previewUrl + pageId);
        } catch (Exception e) {
            e.printStackTrace();
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_CDETAILERROR);
        }


    }

    @Value("${course-publish.publishUrl}")
    String publishUrl;

    /**
     * @Description: 课程发布
     * @Param: courseid
     * @return: 发布结果，响应状态码
     * @Author: Mr.Yuan
     * @Date:
     */
    public PublishResult coursepublish(String courseid) {
        if (StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseid);
        if (!optionalCourseBase.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NULL);
        }
        CourseBase courseBase = optionalCourseBase.get();
//        将页面信息存入页面管理数据库
        CmsPage cmsPage = new CmsPage();
        //站点
        cmsPage.setSiteId(publish_siteId);
        //课程预览站点 //模板
        cmsPage.setTemplateId(publish_templateId);
        //页面名称
        cmsPage.setPageName(courseid + ".html");
        // 页面别名
        cmsPage.setPageAliase(courseBase.getName());
        // 页面访问路径
        cmsPage.setPageWebPath(publish_page_webpath);
        // 页面存储路径
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);
        // 数据url
        cmsPage.setDataUrl(publish_dataUrlPre + courseid);
        // 远程请求cms响应发布结果
        PublishResult publishResult = cmsClient.oneKeyPublish(cmsPage);
        // 修改发布状态为已发布
        courseBase.setStatus("202002");
        courseBaseRepository.save(courseBase);
//        将结果存入一张表中
        CoursePub coursePub = getCoursePub(courseid);
        saveCoursePub(courseid, coursePub);
        //        返回结果
        String purl = publishUrl + courseid + ".html";
        publishResult.setPublishUrl(purl);

//        将媒资信息存入对应索引库的表中
        saveTeachplanMediaPub(courseid);

        return publishResult;
    }

    /**
     * @Description: 查询课程信息
     * @Param: courseid
     * @return: course
     * @Author: Mr.Yuan
     * @Date:
     */
    public CourseViewResult courseView(String courseid) {
        if (StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseid);
        if (!optionalCourseBase.isPresent()) {
            return new CourseViewResult(CourseCode.COURSE_NULL, null);
        }
        CourseBase courseBase = optionalCourseBase.get();
        return new CourseViewResult(CommonCode.SUCCESS, courseBase);
    }

    /**
     * @Description: 将课程信息，营销信息，课程计划，存入一张表中方便获取
     * @Param: courseid
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private CoursePub getCoursePub(String courseid) {
        if (StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseid);
        if (!optionalCourseBase.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NULL);
        }
        CourseBase courseBase = optionalCourseBase.get();
        Optional<CourseMarket> optionalCourseMarket = courseMarketRepository.findById(courseid);
        if (!optionalCourseMarket.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_TEACH_NULL);
        }
        CourseMarket courseMarket = optionalCourseMarket.get();
        Optional<CoursePic> optionalCoursePic = coursePicRepository.findById(courseid);
        if (!optionalCoursePic.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PIC_NULL);
        }
        CoursePic coursePic = optionalCoursePic.get();
//        List<Teachplan> teachplans = teachplanRepository.findByCourseid(courseid);
        TeachplanNode teachplan = courseMapper.findById(courseid);

        if (teachplan == null) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_PUBLISH_COURSEIDISNULL);
        }
        CoursePub coursePub = new CoursePub();
        BeanUtils.copyProperties(courseBase, coursePub);
        BeanUtils.copyProperties(courseMarket, coursePub);
        BeanUtils.copyProperties(coursePic, coursePub);
//        将课程计划转为json字符串
        String jsonString = JSON.toJSONString(teachplan);
        coursePub.setTeachplan(jsonString);
//        设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        Date date = new Date();
        String format = simpleDateFormat.format(date);
        coursePub.setTimestamp(date);
        coursePub.setPubTime(format);
        return coursePub;
    }

    /**
     * @Description: 将合并好的课程存入一 表中
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    @Autowired
    CoursePubRepository coursePubRepository;

    private void saveCoursePub(String courseid, CoursePub coursePub) {
        if (StringUtils.isEmpty(courseid) || coursePub == null) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        if (!coursePub.getId().equals(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.SERVER_ERROR);
        }
        Optional<CoursePub> coursePubOptional = coursePubRepository.findById(courseid);
        CoursePub pub = null;
        if (coursePubOptional.isPresent()) {
//            更新
            pub = coursePubOptional.get();
            BeanUtils.copyProperties(coursePub, pub);
            coursePubRepository.save(pub);
        } else {
//            直接存入
            coursePubRepository.save(coursePub);
        }
    }

    @Autowired
    TeachplanMediaRepository teachplanMediaRepository;

    /**
     * @Description: 添加媒资信息
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    public ResponseResult savemedia(TeachplanMedia teachplanMedia) {
        if (teachplanMedia == null) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
        String courseId = teachplanMedia.getCourseId();
        String mediaFileOriginalName = teachplanMedia.getMediaFileOriginalName();
        String mediaId = teachplanMedia.getMediaId();
        String mediaUrl = teachplanMedia.getMediaUrl();
        String teachplanId = teachplanMedia.getTeachplanId();
        if (StringUtils.isEmpty(courseId) || StringUtils.isEmpty(mediaFileOriginalName) || StringUtils.isEmpty(mediaId) ||
                StringUtils.isEmpty(mediaUrl) || StringUtils.isEmpty(teachplanId)
        ) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
//        判断课程计划是否存在，以及课程等级是否符合
        Optional<Teachplan> optionalTeachplan = teachplanRepository.findById(teachplanId);
        if (!optionalTeachplan.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_TEACH_NULL);
        }
        Teachplan teachplan = optionalTeachplan.get();
        String grade = teachplan.getGrade();
        if (!grade.equals("3")) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_TEACHPLAN_GRADE_ERROR);
        }
//        查询课程是否存在
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseId);
        if (!optionalCourseBase.isPresent()) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NULL);
        }
//      查询媒资信息是否存在
        Optional<TeachplanMedia> optionalTeachplanMedia = teachplanMediaRepository.findById(teachplanId);
        if (optionalTeachplanMedia.isPresent()) {
//            修改
            TeachplanMedia media = optionalTeachplanMedia.get();
            BeanUtils.copyProperties(teachplanMedia, media);
            teachplanMediaRepository.save(media);
        } else {
//            新建存储
            teachplanMediaRepository.save(teachplanMedia);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * @Description: 将媒资信息存入对应索引库的表中
     * @Param:
     * @return:
     * @Author: Mr.Yuan
     * @Date:
     */
    private void saveTeachplanMediaPub(String courseid) {
        if (StringUtils.isEmpty(courseid)) {
            throw CustomExcetionCast.getCusException(CommonCode.INVALIDPARAM);
        }
//        先删除在插入
        List<TeachplanMediaPub> mediaPubs = teachplanMediaPubRepository.findByCourseId(courseid);
        List<TeachplanMedia> media = teachplanMediaRepository.findByCourseId(courseid);
        if (media == null) {
            throw CustomExcetionCast.getCusException(CourseCode.COURSE_NULL);
        }
//        删除
        if (mediaPubs != null) {
            teachplanMediaPubRepository.deleteByCourseId(courseid);
        }
        for (TeachplanMedia tm : media
        ) {
            TeachplanMediaPub tmp = new TeachplanMediaPub();
            tmp.setTimestamp(new Date());
            BeanUtils.copyProperties(tm, tmp);
            //        存入数据库
            teachplanMediaPubRepository.save(tmp);
        }

    }
}